<template>
  <div v-page-show="{
    show: operate?.checkedProject,
    text: `请先选择项目`
  }">
    <RePage>
      <div class="h-full">
        <splitpane :splitSet="settingLR">
          <template v-slot:paneL>
            <div class="pr-[16px] h-full">
              <treeList ref="treeListRef" :treeProops="treeProops" :treeEvents="treeEvents" :inputProops="inputProops"
                :inputEvents="inputEvents" :pageShow="false" :inputShow="true" />
            </div>
          </template>
          <template #paneR>
            <RePage class="nominheihgt" v-page-show="{
    show: searchForm.productId !== null,
    text: `请选择产品后查看`
  }">
              <div class="pl-[16px]">
                <MyFormCreate :clear-event="getTableList" v-model="searchForm" :rule="searchFormRules" :key="key">
                  <template #field-createdAt="scope">
                    <el-form-item>
                      <el-date-picker type="daterange" range-separator="至" start-placeholder="开始时间"
                        end-placeholder="结束时间" value-format="YYYY-MM-DD" placeholder="请选择创建时间" style="width: 100%"
                        v-model="searchForm.createdAt" @change="dateChange" />
                    </el-form-item>
                  </template>
                  <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>

                  <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
                </MyFormCreate>

                <div>
                  <el-button v-auth="'business.alarm.rules.reset'" type="primary" plain
                    @click="datareset()">恢复默认</el-button>
                  <el-button v-auth="'business.alarm.rules.sync'" type="primary" plain @click="syncdatas">同步</el-button>
                </div>
                <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)"
                  showOverflowTooltip border @selection-change="selectionChange" :isShowPag="false">
                  <template #alarmLevel="{ row }">
                    <el-select v-model="row.alarmLevel" @change="changelevel($event, row)"
                      :disabled="!haveRole('business.alarm.rules.level')">
                      <el-option :label="item.label" :value="item.value" v-for="item in EVENTLEVEL"></el-option>
                    </el-select>
                  </template>
                  <template #status="{ row }">
                    <!-- <el-space>
            <el-switch v-model="row.status" />
          </el-space> -->
                    <el-select v-model="row.status" @change="changestatus($event, row)"
                      :disabled="!haveRole('business.alarm.rules.status')">
                      <el-option :label="item.label" :value="item.value" v-for="item in STRATEGYSTATUS"></el-option>
                    </el-select>
                  </template>
                  <template #action="{ row }">
                    <el-space>
                      <sj-link v-auth="'business.alarm.rules.reset'" custom-type="sblue" :underline="false"
                        @click="datareset(row)">恢复默认</sj-link>
                    </el-space>
                  </template>
                </pure-table>
                <!-- <div class="h-[80vh] bg-[red]"></div> -->
                <div class="mt-5">
                  <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.limit" background
                    :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList"
                    @current-change="getTableList" />
                </div>
              </div>
            </RePage>
          </template>
        </splitpane>
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import treeList from "@/components/treeList/treeList.vue";
import splitpane, { ContextProps } from "@/components/ReSplitPane";
import { STRATEGYSTATUS, EVENTLEVEL } from "@/constant/alarm-mangenment";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h } from "vue";
import { PAGE_LAYOUT } from "@/constant";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getInfo,
  addInfo,
  editInfo,
  deleteInfo
} from "@/api/operate/alarm-management/notification-record/index";
import { haveRole } from '@/utils/functions'
import {
  getList,
  alarmreset,
  alarmsync,
  alarmstatus,
  alarmlevel,
  alarmproduct
} from "@/api/operate/alarm-management/alarm-rules/index";
import {
  usePageVariablesStoreHook,
  UNIT_TYPE_VIEW_Map
} from "@/store/modules/pageVariables";
const operate = usePageVariablesStoreHook().getOperate();
import { titles, defaultSearchForm, prompt, defaultInfoForm } from "./index";
import { addDialog } from "@/components/ReDialog";
import {
  cloneDeep,
  isAllEmpty,
  deviceDetection,
  debounce
} from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
const treeListRef = ref();
const searchForm = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
//树状图
const checkedProject = ref(0);
const isLoading = ref(true);
const formRef = ref();
const treeRef = ref();
const projectList = ref([]);
const checkedUnitId = ref(null);
const inputProops = {
  placeholder: "请输入产品类型"
};
const inputChange = e => {
  treeRef.value.filter(e);
  // loadProjectList(e)
};
const inputEvents = {
  input: inputChange
};

//表格
const tableData = reactive({
  data: [],
  total: 0
});

const searchFormRules = [
  {
    type: "input",
    field: "eventName",
    title: "事件名称",
    value: null,
    props: {
      placeholder: "请选择事件名称",
      clearable: true
    }
  },
  {
    type: "select",
    field: "status",
    title: "是否启用",
    value: null,
    options: STRATEGYSTATUS,
    props: {
      placeholder: prompt.status,
      clearable: true
    }
  },
  {
    type: "select",
    field: "alarmLevel",
    title: "事件等级",
    value: null,
    options: EVENTLEVEL,
    props: {
      placeholder: "请选择事件等级",
      clearable: true
    }
  },

  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
];
const selectionData = ref([]);
const roleTableConfig = [
  { prop: "id", label: titles.id, width: 100, fixed: 'left' },
  { prop: "productName", label: "产品类型", minWidth: 120 },
  { prop: "productAlarmTitle", label: "告警事件名称", minWidth: 120 },
  { slot: "status", label: "是否启用", minWidth: 100 },
  { slot: "alarmLevel", label: "事件等级", minWidth: 100 },
  { prop: "updatedByName", label: "编辑人", minWidth: 100 },
  { prop: "updatedAt", label: "编辑时间", minWidth: 120 },
  { slot: "action", label: titles.action, width: 150, fixed: "right" }
];
//树状图
//获取数据
const keyvalue = ref(0);
const defultProjectList = () => [];
const loadProjectList = (e?) => {
  return new Promise((resolve, reject) => {
    isLoading.value = true;
    alarmproduct({ productName: e ? e : "" })
      .then(res => {
        res.result.data.unshift({
          id: "0",
          productName: "全部"
        });
        projectList.value = res.result.data;
      })
      .finally(() => {
        isLoading.value = false;
        resolve('');
      });
    checkedProject.value = 0;
  })
};
const checkproductId = ref(0)
const handleNodeClick = data => {
  checkproductId.value = data.id;
  getTableList();
};
const handleCheckChange = (data, isChecked) => {
  if (isChecked) {
    treeRef.value.setCheckedNodes([data], false);
    checkedUnitId.value = data.value;
    // loadProjectList();
  }
};
const filterMethod = (query, node) => {
  return node.productName.includes(query);
};

const props = {
  label: "productName",
  value: "id"
  // children: "children",
  // isLeaf: "isLeaf"
};
const treeProops = ref({
  props: props,
  data: projectList,
  nodeKey: "productId",
  "item-size": 46,
  "highlight-current": true,
  "filter-method": filterMethod
});
const treeEvents = {
  nodeClick: handleNodeClick
};
onMounted(() => {
  loadProjectList().then(() => {
    treeRef.value = treeListRef.value.getTreeRef()
    treeRef.value.setCurrentKey(projectList.value[0].id);
    searchForm.value.buildingId = projectList.value[0].id
    getTableList()
  })
});
const settingLR: ContextProps = reactive({
  minPercent: 10,
  maxPercent: 10,
  defaultPercent: 15,
  split: "vertical"
});
// 获取列表数据
const getTableList = () => {
  getList({ ...searchForm.value, productId: checkproductId.value }).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  });
};
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchForm.value, defaultSearchForm());
  key.value++;
  getTableList();
};
const dateChange = e => {
  if (e) {
    searchForm.value.startTime = e[0];
    searchForm.value.endTime = e[1];
  } else {
    searchForm.value.startTime = '';
    searchForm.value.endTime = '';
  }
  getTableList()
};
// 详情
const info = row => {
  addDialog({
    title: `详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoForm()
      };
      getInfo({ id: row.id })
        .then(res => {
          if (res.code == 200) {
            showInfo.value = res.result;
            options.props.formInline = res.result;
          }
        })
        .finally(() => {
          options.props.isLoading = false;
        });
    }
  });
};
//改变状态
const changestatus = (e, row) => {
  alarmstatus({ id: row.id, status: e }).then(res => {
    if (res.code == 200) {
      ElMessage.success(res.msg);
      getTableList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
//改变事件等级
const changelevel = (e, row) => {
  alarmlevel({ id: row.id, alarmLevel: e }).then(res => {
    if (res.code == 200) {
      ElMessage.success(res.msg);
      getTableList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};
// 新增
const add = row => {
  showInfo.value = {};
  openDialog();
};
// 编辑
const edit = row => {
  showInfo.value = {};
  openDialog("编辑", row);
};
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(`确认删除${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteInfo({
      ids: row ? [row.id] : selectionData.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getTableList();
      }
    });
  });
};
//恢复默认
const datareset = (row?) => {
  console.log(row, "skdfj");

  ElMessageBox.confirm(`确认恢复默认${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    alarmreset({ ruleId: row ? row.id : '', isAll: row ? false : true, projectId: operate.checkedProject }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: res.msg
        });
        getTableList();
      } else {
        ElMessage({
          type: "error",
          message: res.msg
        });
      }
    });
  });
};
//同步数据
const syncdatas = row => {
  ElMessageBox.confirm(`确认同步数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    alarmsync({ projectId: operate.checkedProject, productId: checkproductId.value }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: res.msg
        });
        getTableList();
      } else {
        ElMessage({
          type: "error",
          message: res.msg
        });
      }
    });
  });
};
// 开启弹窗
const openDialog = (title = "新增", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm()
        };
        getInfo({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              showInfo.value = res.result;
              options.props.formInline = res.result;
            }
          })
          .finally(() => {
            options.props.isLoading = false;
          });
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm()
        };
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "新增") {
            DebounceAddInfo(formData)
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          } else {
            DebounceEditInfo(formData)
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          }
        }
      });
    }
  });
};
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped>
.warp {
  // height: calc(100vh - 182px);
  min-height: calc(100vh - 146px);
}
</style>
